<style>
    form[lay-filter="robotTaskForm"] .layui-form-label {
        width: 100px;
        padding: 9px 5px;
    }

    form[lay-filter="robotTaskForm"] .agvBox > .layui-row {
        margin-bottom: 15px;
    }

    form[lay-filter="robotTaskForm"] .agvBox > .layui-row:first-child > div:last-child > a {
        display: none;
    }
</style>
<!-- 正文开始 -->
<div class="layui-fluid">
    <div class="layui-card">
        <div class="layui-card-body">
            <!-- 头部操作栏 -->
            <div class="layui-form lay-header">
                <div class="toolbar">
                    <div class="layui-form-item lay-query-content">
                        <div class="lay-query-box">
                            <div class="query-lt">
                                <div class="layui-inline">
                                    <label class="layui-form-label w-auto">任务模板名称：</label>
                                    <div class="layui-input-inline">
                                        <input name="name" class="layui-input" type="text" placeholder="请输入任务模板名称"/>
                                    </div>
                                </div>
                                <div class="layui-inline">
                                    <label class="layui-form-label w-auto">任务模板编号：</label>
                                    <div class="layui-input-inline">
                                        <input name="code" class="layui-input" type="text" placeholder="请输入任务模板编号"/>
                                    </div>
                                </div>
                                <div class="layui-inline">
                                    <button class="layui-btn icon-btn color-green" lay-filter="formSubSearchLog" layui-form-keyDownSearch="true" lay-submit>查询</button>
                                    <button class="layui-btn icon-btn color-white" lay-filter="resets" lay-submit>重置</button>
                                </div>
                            </div>
                            <div class="query-rt"></div>
                        </div>
                    </div>
                </div>
                <div class="lay-btn-rows">
                    <div class="lay-btn-box">
                        <div class="lay-btn-lt">
                            <button id="robotTaskBtnAdd" class="layui-btn icon-btn color-reseda">创建
                            </button>
                        </div>
                        <div class="lay-btn-rt">
                        </div>
                    </div>
                </div>
            </div>

            <!-- 表格 -->
            <table class="layui-table" id="robotTaskTable" lay-filter="robotTaskTable"></table>
        </div>
    </div>
</div>

<!-- 表格操作列 -->
<script type="text/html" id="robotTaskTableBar">
    <a class="layui-btn layui-btn-primary layui-btn-xs" lay-event="edit">修改</a>
    <a class="layui-btn layui-btn-danger layui-btn-xs" lay-event="del">删除</a>
    <a class="layui-btn layui-btn-normal layui-btn-xs" lay-event="exe">执行</a>
</script>

<!-- 表单弹窗 -->
<script type="text/html" id="robotTaskForm">
    <form lay-filter="robotTaskForm" class="layui-form model-form"
          style="padding: 5px 30px 0 30px;height: calc(100% - 5px);overflow: hidden;">
        <div class="open-details-box" style="height: calc(100% - 75px); overflow-y: scroll;">
            <input name="id" type="hidden"/>
            <div class="layui-form-item">
                <label class="layui-form-label">任务类型</label>
                <div class="layui-input-block">
                    <select name="instructId" id="instructId" lay-filter="instructId" lay-verify="required"
                            required></select>
                </div>
            </div>
            <div class="layui-form-item">
                <label class="layui-form-label">任务名称</label>
                <div class="layui-input-block">
                    <input name="name" placeholder="请输入任务名称" type="text" class="layui-input" lay-verify="required"
                           required/>
                </div>
            </div>
            <div class="layui-form-item">
                <label class="layui-form-label">任务编号</label>
                <div class="layui-input-block">
                    <input name="code" placeholder="请输入任务编号" type="text" class="layui-input" lay-verify="required"
                           required/>
                </div>
            </div>
            <div class="layui-form-item" style="margin-top: 30px">
                <label class="layui-form-label"></label>
                <a id="robotTaskAddAgv" class="layui-btn">添加</a>
            </div>
            <div class="agvBox" id="agvBox">
                <div class="layui-row">
                    <div class="layui-col-md3">
                        <label class="layui-form-label">agv起点</label>
                        <div class="layui-input-inline">
                            <select name="agvFrom" lay-filter="agvFrom" lay-verify="required" required></select>
                        </div>
                    </div>
                    <div class="layui-col-md3">
                        <label class="layui-form-label">起点动作点位</label>
                        <div class="layui-input-inline">
                            <select name="fromPoint" lay-filter="fromPoint" lay-verify="required" required></select>
                        </div>
                    </div>
                    <div class="layui-col-md3">
                        <label class="layui-form-label">agv目的点</label>
                        <div class="layui-input-inline">
                            <select name="agvTo" lay-filter="agvTo" lay-verify="required" required></select>
                        </div>
                    </div>
                    <div class="layui-col-md3">
                        <label class="layui-form-label">目的点动作点位</label>
                        <div class="layui-input-inline">
                            <select name="toPoint" lay-filter="toPoint" lay-verify="required" required></select>
                        </div>
                        <a class="layui-btn layui-btn-danger layui-btn-xs agvDel"><i class="layui-icon">&#x1006;</i></a>
                    </div>
                </div>
            </div>

        </div>
        <div class="layui-form-item text-right">
            <button class="layui-btn layui-btn-primary" type="button" ew-event="closeDialog">取消</button>
            <button class="layui-btn" lay-filter="robotTaskFormSubmit" lay-submit>保存</button>
        </div>
    </form>
</script>

<!-- js部分 -->
<script>
    layui.use(['layer', 'form', 'table', 'admin'], function () {
        var $ = layui.jquery;
        var layer = layui.layer;
        var form = layui.form;
        var table = layui.table;
        var config = layui.config;
        var admin = layui.admin;
        var upload = layui.upload;

        // 渲染表格
        var insTb = table.render({
            elem: '#robotTaskTable',
            url: config.base + 'enterprise/robot/admin/robotTask/list',
            page: true,
            cellMinWidth: 100,
            cols: [[
                {field: 'number', title: '序号', type: 'numbers'}
                , {field: 'creatorName', sort: true, title: '创建人'}
                , {
                    field: 'instructId', sort: false, title: '任务类型', templet: function (d) {
                        let map = '';
                        admin.reqSync('enterprise/robot/admin/robotInstruct/list', {id: d.instructId}, function (res) {
                            if (200 == res.code && res.data.length != 0) {
                                map = res.data[0].name;
                            }
                        }, 'GET', true);
                        return map;
                    }
                }
                , {field: 'name', sort: true, title: '任务名称'}
                , {field: 'code', sort: true, title: '任务编号'}
                , {
                    field: 'agvFrom', sort: false, title: 'agv起点', templet: function (d) {
                        let map = '';
                        admin.reqSync('enterprise/robot/admin/robotStation/list', {id: d.agvFrom}, function (res) {
                            if (200 == res.code && res.data.length != 0) {
                                map = res.data[0].name;
                            }
                        }, 'GET', true);
                        return map;
                    }
                }
                , {
                    field: 'agvTo', sort: false, title: 'agv目的点', templet: function (d) {
                        let map = '';
                        admin.reqSync('enterprise/robot/admin/robotStation/list', {id: d.agvTo}, function (res) {
                            if (200 == res.code && res.data.length != 0) {
                                map = res.data[0].name;
                            }
                        }, 'GET', true);
                        return map;
                    }
                }
                , {
                    field: 'fromPoint', sort: false, title: '起点动作点位', templet: function (d) {
                        let map = '';
                        admin.reqSync('enterprise/robot/admin/robotPoint/list', {id: d.fromPoint}, function (res) {
                            if (200 == res.code && res.data.length != 0) {
                                map = res.data[0].name;
                            }
                        }, 'GET', true);
                        return map;
                    }
                }
                , {
                    field: 'toPoint', sort: false, title: '目的点动作点位', templet: function (d) {
                        let map = '';
                        admin.reqSync('enterprise/robot/admin/robotPoint/list', {id: d.toPoint}, function (res) {
                            if (200 == res.code && res.data.length != 0) {
                                map = res.data[0].name;
                            }
                        }, 'GET', true);
                        return map;
                    }
                }
                , {field: 'createTime', sort: true, title: '创建时间'}
                , {align: 'center', toolbar: '#robotTaskTableBar', title: '操作', width: 200}
            ]],
            done: function (res, curr, count) {
            }
        });

        // 工具条点击事件
        table.on('tool(robotTaskTable)', function (obj) {
            var data = obj.data;
            if (obj.event === 'edit') { //修改
                showEditModel(data);
            } else if (obj.event === 'del') { // 删除
                doDelete(obj);
            } else if (obj.event === 'exe') { // 执行
                doExe(obj);
            }
        });

        //随机字符串10长 动作块用
        function  randomChar() {
            let x = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
            let tmp = "";
            let timestamp = new Date().getTime();
            for (let i = 0; i < 10; i++) {
                tmp += x.charAt(Math.ceil(Math.random() * 100000000) % x.length);
            }
            return timestamp + tmp;
        }

        //执行
        function doExe(obj) {
            layer.confirm('确定要执行吗？', {
                offset: '65px',
                skin: 'layui-layer-admin'
            }, function (i) {
                layer.close(i);
                //layer.load(2);
                console.log("11")
                admin.req('enterprise/robot/admin/robotTaskDetail/doTask',obj.data,function(res){
                    if (res.code == 200) {
                        layer.msg(res.msg, {icon: 1});
                    } else {
                        layer.msg(res.msg, {icon: 2});
                    }
                }, 'GET', true);
                /*console.log(obj.data)
                //定义唯一编号 运单id
                let uniqueCode='';
                //获取唯一编号
                admin.req('enterprise/robot/admin/robotTaskDetail/getUniqueCode',{},function(res){
                    if(res.code==200){
                        //定义下运单的参数  取货第一个点位
                        let param = {
                            "id":res.data,
                            "blocks": [{
                                "blockId": randomChar(),
                                "location": obj.data.infoList[0].agvFrom
                            }],
                            //不封口 后续可添加动作块
                            "complete": false

                        };
                        admin.req('待添加:8088/setOrder',param,function(res){
                            if(res.code==200){
                                //添加动作块 去剩下的取货点
                                for (let j = 1; j < obj.data.infoList.length; j++) {

                                }
                                //添加动作块 去送货点
                                //封口
                            }
                        }, 'POST', true);
                    }
                }, 'GET', true);*/


            });

        }


        //监听排序
        table.on('sort(robotTaskTable)', function (obj) {
            table.reload('robotTaskTable', {
                initSort: obj
                , where: {
                    sort: obj.field
                    , order: obj.type
                }
            });
        });

        // 添加按钮点击事件
        $('#robotTaskBtnAdd').click(function () {
            showEditModel();
        });

        // 显示编辑弹窗
        function showEditModel(data) {
            admin.open({
                type: 1,
                area: ['1580px', '800px'],
                offset: '65px',
                title: data ? '修改复合机器人任务' : '添加复合机器人任务',
                content: $('#robotTaskForm').html(),
                success: function () {
                    admin.reqSync('enterprise/robot/admin/robotInstruct/list', {limit: 9999}, function (res) {
                        if (200 == res.code) {
                            loadSelectHtml(res.data, "请选择类型", "instructId", 0);
                        } else {
                            layer.msg('获取类型失败', {icon: 2, time: 1000});
                        }
                    }, 'GET', true);


                    admin.reqSync('enterprise/robot/admin/robotStation/list', {limit: 99999}, function (res) {
                        if (200 == res.code) {
                            loadSelectHtml(res.data, "请选择agv起点", "agvFrom", 3);
                        }
                    }, 'GET', true);

                    admin.reqSync('enterprise/robot/admin/robotStation/list', {limit: 99999}, function (res) {
                        if (200 == res.code) {
                            loadSelectHtml(res.data, "请选择agv目的点", "agvTo", 3);
                        }
                    }, 'GET', true);


                    if (data) {
                        if (data.infoList && data.infoList.length > 0) {
                            data.infoList.forEach((item, index) => {
                                if (index === 0) {
                                    $('#agvBox>.layui-row').eq(index).attr('id', item.id);
                                    $('#agvBox>.layui-row').eq(index).find('select[name="agvFrom"]').val(item.agvFrom);
                                    $('#agvBox>.layui-row').eq(index).find('select[name="agvTo"]').val(item.agvTo);
                                    fromPointLoading('enterprise/robot/admin/robotPoint/list?stationCode=' + item.agvFrom, item.agvFrom, 'fromPoint', $('#agvBox>.layui-row').eq(index), item.fromPoint);
                                    fromPointLoading('enterprise/robot/admin/robotPoint/list?stationCode=' + item.agvTo, item.agvTo, 'toPoint', $('#agvBox>.layui-row').eq(index), item.toPoint)
                                } else {
                                    let html = $('#agvBox > .layui-row').eq(0).clone().attr('id', item.id);
                                    $('#agvBox').append(html);
                                    $('#agvBox>.layui-row').eq(index).find('select[name="agvFrom"]').val(item.agvFrom);
                                    $('#agvBox>.layui-row').eq(index).find('select[name="agvTo"]').val(item.agvTo);
                                    fromPointLoading('enterprise/robot/admin/robotPoint/list?stationCode=' + item.agvFrom, item.agvFrom, 'fromPoint', $('#agvBox>.layui-row').eq(index), item.fromPoint);
                                    fromPointLoading('enterprise/robot/admin/robotPoint/list?stationCode=' + item.agvTo, item.agvTo, 'toPoint', $('#agvBox>.layui-row').eq(index), item.toPoint)
                                }
                            })
                        }

                        form.render('select');

                    }

                    $('#robotTaskAddAgv').click(function () {
                        let html = $('#agvBox > .layui-row').eq(0).clone().attr('id', '');
                        $('#agvBox').append(html);
                        form.render('select');
                    });

                    $('#agvBox').delegate('.agvDel', 'click', function () {
                        $(this).parents('.layui-row').remove();
                    });

                    form.on('select', function (data) {
                        let name = $(data.elem).attr('name');
                        let parentsEle = $(data.elem).parents('.layui-row');

                        if (name == 'agvFrom') {
                            fromPointLoading('enterprise/robot/admin/robotPoint/list?stationCode=' + data.value, data.value, 'fromPoint', parentsEle)
                        } else if (name == 'agvTo') {
                            fromPointLoading('enterprise/robot/admin/robotPoint/list?stationCode=' + data.value, data.value, 'toPoint', parentsEle)
                        } else {
                            return false;
                        }
                    });

                    function fromPointLoading(_url, _value, _name, _parentsEle, _selected) {
                        if (!_value || _value == '') {
                            showSelectHtml([], '请选择', _name, 0, _parentsEle);
                        } else {
                            admin.req(_url, {}, function (res) {
                                if (200 == res.code) {
                                    showSelectHtml(res.data, '请选择', _name, 0, _parentsEle, _selected);
                                } else {
                                    showSelectHtml([], '请选择', _name, 0, _parentsEle);
                                }
                            }, 'GET',true);
                        }
                    }


                    form.val('robotTaskForm', data);
                    // 表单提交事件
                    form.on('submit(robotTaskFormSubmit)', function (d) {
                        layer.load(2);
                        let infoList = [];
                        $('#agvBox>.layui-row').each((index, elem) => {
                            infoList[index] = {};
                            infoList[index].id = $(elem).attr('id');
                            infoList[index].agvFrom = $(elem).find('select[name="agvFrom"]').val();
                            infoList[index].agvTo = $(elem).find('select[name="agvTo"]').val();
                            infoList[index].fromPoint = $(elem).find('select[name="fromPoint"]').val();
                            infoList[index].toPoint = $(elem).find('select[name="toPoint"]').val();
                        });
                        d.field.infoList = infoList;
                        admin.req(data ? 'enterprise/robot/admin/robotTask/update' : 'enterprise/robot/admin/robotTask/add', JSON.stringify(d.field), function (res) {
                            layer.closeAll('loading');
                            if (res.code == 200) {
                                layer.msg(res.msg, {icon: 1});
                                table.reload('robotTaskTable');
                                layer.closeAll('page');
                            } else {
                                layer.msg(res.msg, {icon: 2});
                            }
                        }, data ? 'PUT' : 'POST', true, 'application/json; charset=utf-8');
                        return false;
                    });
                }
            });
        }

        // 删除
        function doDelete(obj) {
            layer.confirm('确定要删除吗？', {
                offset: '65px',
                skin: 'layui-layer-admin'
            }, function (i) {
                layer.close(i);
                layer.load(2);
                admin.req('enterprise/robot/admin/robotTask/' + obj.data.id, {}, function (res) {
                    layer.closeAll('loading');
                    if (res.code == 200) {
                        layer.msg(res.msg, {icon: 1});
                        obj.del();
                    } else {
                        layer.msg(res.msg, {icon: 2});
                    }
                }, 'DELETE');
            });
        }

        // 搜索
        form.on('submit(formSubSearchLog)', function (data) {
            insTb.reload({where: data.field, page: {curr: 1}}, 'data');
        });

        // 重置搜索
        form.on('submit(resets)', function (data) {
            $(".lay-header").find('select').val("");
            $(".lay-header").find('input').val("");
            var field = data.field;
            for (let key in field) {
                field[key] = ''
            }
            insTb.reload({where: field, page: {curr: 1}}, 'data');
        });

        //option渲染
        function loadSelectHtml(data, tips, htmltarget, type) {
            let html = ' <option value>' + tips + '</option>';
            if (!data || data == null) {
                return;
            }
            for (let i = 0; i < data.length; i++) {
                if (type === 0) {
                    html += `<option value='${data[i].id}'>${data[i].name}</option>`;
                } else if (type === 1) {
                    html += `<option value='${data[i].id}'>${data[i].corporateName}</option>`;
                } else if (type === 3) {
                    html += `<option value='${data[i].code}'>${data[i].name}</option>`;
                }
            }

            $("form select[name='" + htmltarget + "']").html(html);
            form.render('select');
        }

        function showSelectHtml(data, tips, name, type, parentsEle, __selected) {
            let html = ' <option value>' + tips + '</option>';
            if (!data || data == null) {
                return;
            }
            for (let i = 0; i < data.length; i++) {
                if (type === 0) {
                    if (__selected) {
                        html += `<option value='${data[i].id}' ${data[i].id == __selected ? 'selected' : ''}>${data[i].name}</option>`;
                    } else {
                        html += `<option value='${data[i].id}'>${data[i].name}</option>`;
                    }
                } else if (type === 1) {
                    if (__selected) {
                        html += `<option value='${data[i].id}' ${data[i].id == __selected ? 'selected' : ''}>${data[i].corporateName}</option>`;
                    } else {
                        html += `<option value='${data[i].id}'>${data[i].corporateName}</option>`;
                    }


                }
            }

            $(parentsEle).find("select[name='" + name + "']").html(html);
            form.render('select');
        }
    });
</script>